
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:math' as math;
//import 'package:chinese_words/chinese_words.dart';
import 'package:lpinyin/lpinyin.dart';
import 'dart:convert';




//https://blog.csdn.net/ZCC361571217/article/details/129541042
/*class SliverForListPage extends StatefulWidget {
  const SliverForListPage({Key? key}) : super(key: key);

  @override
  State<SliverForListPage> createState() => _SliverForListPageState();
}

class _SliverForListPageState extends State<SliverForListPage> {
  Color getRandomColor({int r = 255, int g = 255, int b = 255, a = 255}) {
    if (r == 0 || g == 0 || b == 0) return Colors.black;
    if (a == 0) return Colors.white;
    return Color.fromARGB(
      a,
      r != 255 ? r : math.Random.secure().nextInt(r),
      g != 255 ? g : math.Random.secure().nextInt(g),
      b != 255 ? b : math.Random.secure().nextInt(b),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Sliver用法',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 12),),
      ),
      body: CustomScrollView(
        slivers: [

          SliverList(delegate: SliverChildListDelegate([
            Container(color: getRandomColor(),height: 150,),
            Container(color: getRandomColor(),height: 150,),
            Container(color: getRandomColor(),height: 150,),
          ])),
        ],

      ),
    );
  }
}*/

/*class SliverForListPage extends StatefulWidget {
  const SliverForListPage({Key? key}) : super(key: key);

  @override
  State<SliverForListPage> createState() => _SliverForListPageState();
}

class _SliverForListPageState extends State<SliverForListPage> {
  Color getRandomColor({int r = 255, int g = 255, int b = 255, a = 255}) {
    if (r == 0 || g == 0 || b == 0) return Colors.black;
    if (a == 0) return Colors.white;
    return Color.fromARGB(
      a,
      r != 255 ? r : math.Random.secure().nextInt(r),
      g != 255 ? g : math.Random.secure().nextInt(g),
      b != 255 ? b : math.Random.secure().nextInt(b),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Sliver用法',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 12),),
      ),
      body: CustomScrollView(
        slivers: [
          SliverList(delegate: SliverChildBuilderDelegate((context, index) => Container(color: getRandomColor(),height: 150,))),
        ],

      ),
    );
  }
}*/

class SliverForGridViewPage extends StatefulWidget {
  const SliverForGridViewPage({Key? key}) : super(key: key);

  @override
  State<SliverForGridViewPage> createState() => _SliverForGridViewPageState();
}

class _SliverForGridViewPageState extends State<SliverForGridViewPage> {
  Color getRandomColor({int r = 255, int g = 255, int b = 255, a = 255}) {
    if (r == 0 || g == 0 || b == 0) return Colors.black;
    if (a == 0) return Colors.white;
    return Color.fromARGB(
      a,
      r != 255 ? r : math.Random.secure().nextInt(r),
      g != 255 ? g : math.Random.secure().nextInt(g),
      b != 255 ? b : math.Random.secure().nextInt(b),
    );
  }

  List<Widget> list = [];

  final int wordsCount = 4;


  List<String> list_word = [];

  void initWords() {
    if(list_word.length<=0) {
      for (var i = 0; i < wordsCount; i++) {
        list_word.add("A");
      }
    }
  }

  void updateWords() {

    for(var i = 0;i<wordsCount;i++){
      setState(() {
      //list_word[i] = "";


        getWord()
            .then((value) => list_word[i]=value)
            .catchError((error, stackTrace) => print(stackTrace));
      });
    }

    // int listLength = list_word.length-0>0?list_word.length:20;
    // print("listLength222:" + listLength.toString());
    // for(var i = 0;i<listLength;i++){
    //   print("list_word222[i]:" + list_word[i]);
    // }
  }


  List<Widget> generateWidgetList(){


    // // 模拟网络请求
    // Future<String> requestNetwork(String name){
    //   return Future.delayed(Duration(seconds: 1), (){
    //     return "Hello, i am $name";
    //   });
    // }



    // for(var i = 0;i<100;i++){
    //   list_word[i] = await getWord();
    // }


    Container containerBtn =  Container(
      color: Colors.white,
      height: 200,
      child: Center(
        child: Row(
          children: [
            ElevatedButton(
              child: const Text('Update1'),
              onPressed: () {
                updateWords(); // 点击按钮后调用updateButtons函数进行更新操作
              },
            ),
          ],
        ),
      ),
    );

    setState(() {
      //list.clear();
    });
    int listLength = list_word.length-0>0?list_word.length:wordsCount;
    if(list_word.length>0&& listLength>0){
      for(var i = 0;i<listLength;i++){
      //for(var i = 0;i<list.length-3;i++){
        list.removeAt(0);
      }
    }
    list.add(containerBtn);

    print("listLength:" + listLength.toString());
    for(var i = 0;i<listLength;i++){
      //print("list_word[i]:" + list_word[i]);
      if(i==0){
         initWords();
      }
      Container container =  Container(
        color: getRandomColor(),
        height: 150,
        child: Center(
          child: Text(
            list_word[i], // 要显示的文字
            style: const TextStyle(
              fontSize: 32, // 文字大小
              color: Colors.white, // 文字颜色
            ),
          ),
        ),
      );
      list.add(container);
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: /*const Text('SliverGrid.extent',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 12),),*/
        PreferredSize(
          preferredSize: const Size.fromHeight(50),
          child: Container(
            padding: const EdgeInsets.only(left: 28, right: 28, top: 0),
            child: ElevatedButton(
              child: const Text('Update'),
              onPressed: () {
                updateWords(); // 点击按钮后调用updateButtons函数进行更新操作
              },
            ),
          ),
        ),
      ),


      body:
                 Container(
                  color: Colors.red,
                  child:
                  CustomScrollView(
                    slivers: [
                      SliverGrid.extent(maxCrossAxisExtent: 100,children: generateWidgetList(),),
                    ],
                  ),
                ),
    );
  }
}

// import 'dart:math';
// import 'package:chinese_words/chinese_words.dart';

/*void main() {
  // 生成一组随机汉字
  String randomWord = generateWord();

  // 打印随机汉字
  print(randomWord);

  // 获取随机汉字的拼音
  String pinyin = ChineseHelper.getPinyin(randomWord);

  // 打印拼音
  print(pinyin);
}*/

//https://pub-web.flutter-io.cn/documentation/lpinyin/latest/
// 生成一个随机汉字
String generateWord(int i) {
  /*final _random = math.Random();
  String word = '';

  // 生成随机的汉字字符集
  var characters = CHINESE_WORDS.characters;

  // 从字符集中随机选择一个汉字
  for (var i = 0; i < _random.nextInt(3) + 1; i++) {
    word += String.fromCharCode(characters.codeUnitAt(_random.nextInt(characters.length)));
  }

  return word;*/
  String text = "福";
  if(i==1) {
    getWord();
  }
  //字符串拼音首字符
  return PinyinHelper.getPinyinE(text, separator: " ", defPinyin: '#', format: PinyinFormat.WITHOUT_TONE); // tfgc
  //return getWord();
}


Future<String> getWord() async {

// }
// void main() async {
  var url = Uri.parse('https://www.getrandomthings.com/data/random-chinese-words.php'); // 设置要访问的URL地址
  //var url = Uri.parse('http://baidu.com');
  Map<String, String> headers = {
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
    'x-requested-with': 'XMLHttpRequest',
    'accept-language': 'zh-CN,zh;q=0.9'
  }; // 自定义头部信息


  try {
    var response = await http.post(url, headers: headers, body: 'num=1&add=address&unique=false&num=1&add=address&unique=false'); // 发起GET请求

    //print('Request response with status: ${response.statusCode}.'); // 打印错误信息
    //print('Response body: ${response.body}'); // 输出服务器返回的数据内容
    if (response.statusCode == 200 || response.statusCode == 302) { // 判断返回状态码为200表示成功
      //print('Response body: ${response.body}'); // 输出服务器返回的数据内容
      String res = const Utf8Decoder().convert(response.bodyBytes);
      //print(res); // 打印服务器返回的内容（UTF-8编码）
      String aWord = res.replaceAll("<div class='row'><div class='col-md-4 pt'>", '').substring(0,1);
      print(aWord);

      return Future.value(aWord);
      // 在这里对返回的数据进行处理或者其他操作
    } else {
      print('Request failed with status: ${response.statusCode}.'); // 打印错误信息
      return Future.value("错");
    }
  } catch (e) {
    print('Exception occurred: $e'); // 打印异常信息
    return Future.error(Error());
  }
}

// 自定义按钮组件
class MyButton extends StatefulWidget {
  const MyButton({super.key});

  @override
  _MyButtonState createState() => _MyButtonState();
}

class _MyButtonState extends State<MyButton> {
  String result = ''; // 存放Future结果的变量

  void fetchData() async {
    final data = await getWord(); // 模拟从服务器获取数据的操作

    setState(() {
      result = data; // 更新result变量值
    });
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      child: const Text('Fetch Data'),
      onPressed: () {
        fetchData(); // 点击按钮时调用fetchData函数
      },
    );
  }
}